package com.wyatt.wytplatform.mvvm_login.ui.login

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.wyatt.wytplatform.mvvm_login.data.model.LoginResponse
import com.wyatt.wytplatform.mvvm_login.data.model.UserEntity
import com.wyatt.wytplatform.mvvm_login.data.repository.UserRepository
import com.wyatt.wytplatform.mvvm_login.utils.Resource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class LoginViewModel @Inject constructor(
    private val repository: UserRepository
) : ViewModel() {

    private val _loginState = MutableLiveData<LoginState>()
    val loginState: LiveData<LoginState> = _loginState

    fun login(username: String, password: String) {
        if (username.isBlank() || password.isBlank()) {
            _loginState.value = LoginState.Error("用户名和密码不能为空")
            return
        }

        repository.login(username, password).onEach { result ->
            when (result) {
                is Resource.Loading -> {
                    _loginState.value = LoginState.Loading
                }
                is Resource.Success -> {
                    saveUser(result.data!!)
                    _loginState.value = LoginState.Success(result.data)
                }
                is Resource.Error -> {
                    _loginState.value = LoginState.Error(result.message ?: "未知错误")
                }
            }
        }.launchIn(viewModelScope)
    }

    private fun saveUser(response: LoginResponse) {
        viewModelScope.launch {
            repository.saveUser(
                UserEntity(
                    id = response.id,
                    username = response.username,
                    token = response.token
                )
            )
        }
    }

    sealed class LoginState {
        object Loading : LoginState()
        data class Success(val data: LoginResponse) : LoginState()
        data class Error(val message: String) : LoginState()
    }
}    